package com.sinog.alarm.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

/**
 * @author wangxj
 * @desc TODO
 * @date 2022/11/23 下午4:32
 */
@Configuration
@MapperScan(basePackages = "com.sinog.alarm.mapper.db2", sqlSessionTemplateRef  = "db2SqlSessionTemplate")
public class DataSource2Config {

    /**
     * db2
     */
    @Autowired
    private DataBase2Properties dataBase2Properties;

    @Bean(name = "db2DataSource")
    public DataSource dbDataSource() {
        HikariDataSource hds = new HikariDataSource();
        hds.setDriverClassName(dataBase2Properties.getDriverClassName());
        hds.setJdbcUrl(dataBase2Properties.getUrl());
        hds.setUsername(dataBase2Properties.getUsername());
        hds.setPassword(dataBase2Properties.getPassword());
        hds.setAutoCommit(true);
        return hds;
    }

    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*xml"));
        return bean.getObject();
    }

    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager dbTransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
